// 获取回收员ID
const collectorId = window.location.pathname.split('/').pop();

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化加载数据
    loadOrderTrend();
    loadItemDistribution();
    loadOrders();

    // 绑定状态筛选事件
    document.getElementById('orderStatus').addEventListener('change', function() {
        loadOrders();
    });
});

// 加载订单趋势数据
function loadOrderTrend() {
    fetch(`/admin/collectors/${collectorId}/order-trend`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            const ctx = document.getElementById('orderTrendChart');
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: data.map(item => item.date),
                    datasets: [{
                        label: '订单数量',
                        data: data.map(item => item.count),
                        fill: true,
                        borderColor: '#1890ff',
                        backgroundColor: 'rgba(24, 144, 255, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                stepSize: 1
                            }
                        }
                    }
                }
            });
        })
        .catch(error => {
            console.error('加载订单趋势数据失败:', error);
            showError('订单趋势数据加载失败');
        });
}

// 加载物品分布数据
function loadItemDistribution() {
    fetch(`/admin/collectors/${collectorId}/item-distribution`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            const ctx = document.getElementById('itemDistributionChart');
            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: data.map(item => {
                        switch(item.type) {
                            case 'PLASTIC': return '塑料';
                            case 'PAPER': return '纸类';
                            case 'METAL': return '金属';
                            case 'GLASS': return '玻璃';
                            case 'FABRIC': return '布料';
                            case 'ELECTRONICS': return '电子产品';
                            default: return '其他';
                        }
                    }),
                    datasets: [{
                        data: data.map(item => item.count),
                        backgroundColor: [
                            '#1890ff', '#52c41a', '#faad14', 
                            '#f5222d', '#722ed1', '#13c2c2'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right'
                        }
                    }
                }
            });
        })
        .catch(error => {
            console.error('加载物品分布数据失败:', error);
            showError('物品分布数据加载失败');
        });
}

// 加载订单数据
function loadOrders(page = 0) {
    const status = document.getElementById('orderStatus').value;
    const params = new URLSearchParams({
        page: page,
        size: 10,
        status: status
    });

    fetch(`/admin/collectors/${collectorId}/orders?${params.toString()}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            updateOrderTable(data.content);
            updateOrderPagination(data);
        })
        .catch(error => {
            console.error('加载订单数据失败:', error);
            showError('订单数据加载失败');
        });
}

// 更新订单表格
function updateOrderTable(orders) {
    const tbody = document.getElementById('orderTableBody');
    tbody.innerHTML = '';
    
    orders.forEach(order => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${order.orderNo}</td>
            <td>${formatDateTime(order.appointmentTime)}</td>
            <td>${order.address}</td>
            <td>${formatItemType(order.itemType)}</td>
            <td>${order.actualWeight?.toFixed(1) || '-'}</td>
            <td>${order.price?.toFixed(2) || '-'}</td>
            <td>
                <span class="badge ${getStatusBadgeClass(order.status)}">
                    ${formatStatus(order.status)}
                </span>
            </td>
            <td>
                ${order.rating ? 
                    `<span class="text-warning">
                        ${'★'.repeat(order.rating)}${'☆'.repeat(5-order.rating)}
                    </span>` : 
                    '-'}
            </td>
            <td>
                <button class="btn btn-sm btn-info" onclick="viewOrderDetail(${JSON.stringify(order).replace(/"/g, '&quot;')})">
                    <i class="bx bx-detail"></i> 详情
                </button>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

// 查看订单详情
function viewOrderDetail(order) {
    // 设置基本信息
    document.getElementById('detailOrderNo').textContent = order.orderNo;
    document.getElementById('detailAppointmentTime').textContent = formatDateTime(order.appointmentTime);
    document.getElementById('detailAddress').textContent = order.address;
    document.getElementById('detailContactPhone').textContent = order.contactPhone;
    document.getElementById('detailItemType').textContent = formatItemType(order.itemType);
    document.getElementById('detailItemDescription').textContent = order.itemDescription || '-';
    document.getElementById('detailEstimatedWeight').textContent = order.estimatedWeight?.toFixed(1) || '-';
    document.getElementById('detailActualWeight').textContent = order.actualWeight?.toFixed(1) || '-';
    
    // 设置状态
    const statusBadge = document.getElementById('detailStatus');
    statusBadge.className = `badge ${getStatusBadgeClass(order.status)}`;
    statusBadge.textContent = formatStatus(order.status);
    
    // 设置金额
    document.getElementById('detailPrice').textContent = 
        order.price ? `¥${order.price.toFixed(2)}` : '-';
    
    // 设置评分和评价
    document.getElementById('detailRating').innerHTML = 
        order.rating ? `<span class="text-warning">${'★'.repeat(order.rating)}${'☆'.repeat(5-order.rating)}</span>` : '-';
    document.getElementById('detailComment').textContent = order.comment || '-';
    
    // 设置时间线
    document.getElementById('detailCreateTime').textContent = formatDateTime(order.createTime);
    
    // 完成时间
    const completeTimeItem = document.getElementById('detailCompleteTimeItem');
    if (order.completeTime) {
        document.getElementById('detailCompleteTime').textContent = formatDateTime(order.completeTime);
        completeTimeItem.style.display = 'block';
    } else {
        completeTimeItem.style.display = 'none';
    }
    
    // 取消时间
    const cancelTimeItem = document.getElementById('detailCancelTimeItem');
    if (order.cancelTime) {
        document.getElementById('detailCancelTime').textContent = formatDateTime(order.cancelTime);
        document.getElementById('detailCancelReason').textContent = order.cancelReason || '无原因';
        cancelTimeItem.style.display = 'block';
    } else {
        cancelTimeItem.style.display = 'none';
    }
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('orderDetailModal'));
    modal.show();
}

// 更新订单分页
function updateOrderPagination(data) {
    const pagination = document.getElementById('orderPagination');
    const totalPages = data.totalPages;
    const currentPage = data.number;
    
    let html = '';
    
    // 上一页按钮
    html += `
        <li class="page-item ${currentPage === 0 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadOrders(${currentPage - 1})" tabindex="-1">上一页</a>
        </li>
    `;
    
    // 页码按钮
    for (let i = 0; i < totalPages; i++) {
        html += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" onclick="loadOrders(${i})">${i + 1}</a>
            </li>
        `;
    }
    
    // 下一页按钮
    html += `
        <li class="page-item ${currentPage === totalPages - 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadOrders(${currentPage + 1})">下一页</a>
        </li>
    `;
    
    pagination.innerHTML = html;
}

// 导出订单数据
function exportOrders() {
    const status = document.getElementById('orderStatus').value;
    const params = new URLSearchParams({ status });
    window.location.href = `/admin/collectors/${collectorId}/orders/export?${params.toString()}`;
}

// 工具函数
function formatDateTime(dateTime) {
    if (!dateTime) return '-';
    return new Date(dateTime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function formatItemType(type) {
    const types = {
        'PLASTIC': '塑料',
        'PAPER': '纸类',
        'METAL': '金属',
        'GLASS': '玻璃',
        'FABRIC': '布料',
        'ELECTRONICS': '电子产品'
    };
    return types[type] || '其他';
}

function formatStatus(status) {
    const statuses = {
        'PENDING': '待处理',
        'PROCESSING': '处理中',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
    };
    return statuses[status] || status;
}

function getStatusBadgeClass(status) {
    const classes = {
        'PENDING': 'bg-warning',
        'PROCESSING': 'bg-info',
        'COMPLETED': 'bg-success',
        'CANCELLED': 'bg-secondary'
    };
    return classes[status] || 'bg-secondary';
}

function showError(message) {
    Swal.fire({
        icon: 'error',
        title: '错误',
        text: message,
        timer: 3000,
        showConfirmButton: false
    });
}

// 打开编辑模态框
function editCollector() {
    const modal = new bootstrap.Modal(document.getElementById('editCollectorModal'));
    modal.show();
}

// 更新回收员信息
function updateCollector() {
    const form = document.getElementById('editCollectorForm');
    const formData = new FormData(form);
    const data = Object.fromEntries(formData.entries());
    
    fetch(`/admin/collectors/${collectorId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(collector => {
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('editCollectorModal'));
        modal.hide();
        
        // 显示成功提示
        Swal.fire({
            icon: 'success',
            title: '更新成功',
            text: '回收员信息已更新',
            timer: 2000,
            showConfirmButton: false
        }).then(() => {
            // 刷新页面以显示更新后的信息
            window.location.reload();
        });
    })
    .catch(error => {
        console.error('更新回收员信息失败:', error);
        Swal.fire({
            icon: 'error',
            title: '更新失败',
            text: '更新回收员信息失败，请稍后重试'
        });
    });
}

// 上传头像
function uploadAvatar(input) {
    if (input.files && input.files[0]) {
        // 检查文件大小
        const maxSize = 2 * 1024 * 1024; // 2MB
        if (input.files[0].size > maxSize) {
            Swal.fire({
                icon: 'error',
                title: '文件过大',
                text: '请选择2MB以内的图片文件'
            });
            return;
        }

        // 检查文件类型
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!allowedTypes.includes(input.files[0].type)) {
            Swal.fire({
                icon: 'error',
                title: '文件类型错误',
                text: '请选择JPG、PNG或GIF格式的图片'
            });
            return;
        }

        // 创建FormData对象
        const formData = new FormData();
        formData.append('avatar', input.files[0]);

        // 显示加载提示
        Swal.fire({
            title: '上传中...',
            text: '请稍候',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // 发送请求
        fetch(`/admin/collectors/${collectorId}/avatar`, {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            // 更新预览图
            document.getElementById('avatarPreview').src = data.avatarUrl + '?t=' + new Date().getTime();
            
            // 显示成功提示
            Swal.fire({
                icon: 'success',
                title: '上传成功',
                text: '头像已更新',
                timer: 2000,
                showConfirmButton: false
            });
        })
        .catch(error => {
            console.error('上传头像失败:', error);
            Swal.fire({
                icon: 'error',
                title: '上传失败',
                text: '头像上传失败，请稍后重试'
            });
        });
    }
} 